<template>
  <div class="orginfo-modyfy-container">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btnList="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <page-form
            className="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :label-width="formInfo.labelWidth"
            :rules="formInfo.rules"
          >
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>营业执照</p>
        </div>
        <div class="model-panel-body">
          <page-form
            className="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="certificateOfBusinessInfo.ref"
            :data="certificateOfBusinessInfo.data"
            :field-list="certificateOfBusinessInfo.fieldList"
            :label-width="certificateOfBusinessInfo.labelWidth"
            :rules="certificateOfBusinessInfo.rules"
          >
            <template v-slot:form-licenseFilePath>
              <div class="slot-licenseFilePath">
                <upload-img
                  multiple
                  :action="action"
                  title="营业执照"
                  :responseFn="handleResponse"
                  v-model:value="
                    certificateOfBusinessInfo.data.licenseFilePaths
                  "
                />
              </div>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>第三类医疗器械经营许可证</p>
        </div>
        <div class="model-panel-body">
          <page-form
            className="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="businessLicenseInfo.ref"
            :data="businessLicenseInfo.data"
            :field-list="businessLicenseInfo.fieldList"
            :label-width="businessLicenseInfo.labelWidth"
            :rules="businessLicenseInfo.rules"
          >
            <template v-slot:form-licenseFilePath>
              <div class="slot-licenseFilePath">
                <upload-img
                  multiple
                  :action="action"
                  title="第三类医疗器械经营许可证"
                  :responseFn="handleResponse"
                  v-model:value="businessLicenseInfo.data.licenseFilePaths"
                />
              </div>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>第二类医疗器械经营备案凭证</p>
        </div>
        <div class="model-panel-body">
          <page-form
            className="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="businessRecordCertificate.ref"
            :data="businessRecordCertificate.data"
            :field-list="businessRecordCertificate.fieldList"
            :label-width="businessRecordCertificate.labelWidth"
            :rules="businessRecordCertificate.rules"
          >
            <template v-slot:form-licenseFilePath>
              <div class="slot-licenseFilePath">
                <upload-img
                  multiple
                  :action="action"
                  title="第二类医疗器械经营备案凭证"
                  :responseFn="handleResponse"
                  v-model:value="
                    businessRecordCertificate.data.licenseFilePaths
                  "
                />
              </div>
            </template>
          </page-form>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="modifyOrgInfo">
import { getOrgInformation, updateOrgInformation } from '@/api/core'
const props = defineProps(['visible', 'title', 'data', 'type'])
const { proxy } = getCurrentInstance()
const emits = defineEmits()

const validateIssuingDate = (rule, value, callback) => {
  let data = certificateOfBusinessInfo.value.data
  if (value) {
    if (data.startDate) {
      if (value > data.startDate) {
        callback(new Error('发证日期不能大于营业开始日期'))
      }
    }
    if (data.endDate) {
      if (value > data.endDate) {
        callback(new Error('发证日期不能大于营业截止日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}
const validateStartDate = (rule, value, callback) => {
  let data = certificateOfBusinessInfo.value.data
  if (value) {
    if (data.issuingDate) {
      if (value < data.issuingDate) {
        callback(new Error('营业开始日期不能小于发证日期'))
      }
    }
    if (data.endDate) {
      if (value > data.endDate) {
        callback(new Error('营业开始日期不能大于营业截止日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}
const validateEndDate = (rule, value, callback) => {
  let data = certificateOfBusinessInfo.value.data
  if (value) {
    if (data.issuingDate) {
      if (value < data.issuingDate) {
        callback(new Error('营业截止日期不能小于发证日期'))
      }
    }
    if (data.startDate) {
      if (value < data.startDate) {
        callback(new Error('营业截止日期不能小于营业开始日期'))
      }
    }
    callback()
  } else {
    callback()
  }
} //
const validateBIssuingDate = (rule, value, callback) => {
  let data = businessLicenseInfo.value.data
  if (value) {
    if (data.startDate) {
      if (value > data.startDate) {
        callback(new Error('发证日期不能大于许可期限开始日期'))
      }
    }
    if (data.endDate) {
      if (value > data.endDate) {
        callback(new Error('发证日期不能大于许可期限截止日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}
const validateBStartDate = (rule, value, callback) => {
  let data = businessLicenseInfo.value.data
  if (value) {
    if (data.issuingDate) {
      if (value < data.issuingDate) {
        callback(new Error('许可期限开始日期不能小于发证日期'))
      }
    }
    if (data.endDate) {
      if (value > data.endDate) {
        callback(new Error('许可期限开始日期不能大于许可期限截止日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}
const validateBEndDate = (rule, value, callback) => {
  let data = businessLicenseInfo.value.data
  if (value) {
    if (data.issuingDate) {
      if (value < data.issuingDate) {
        callback(new Error('许可期限截止日期不能小于发证日期'))
      }
    }
    if (data.startDate) {
      if (value < data.startDate) {
        callback(new Error('许可期限截止日期不能小于许可期限开始日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}

// 表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '机构名称', value: 'name', type: 'input', maxlength: 20 },
    { label: '邮编', value: 'zipCode', type: 'input', maxlength: 10 },
    { label: '邮箱', value: 'mail', type: 'input', maxlength: 48 },
    { label: '地址', value: 'cities', type: 'city-model' },
    { label: '联系电话', value: 'phone', type: 'input', maxlength: 20 },
    { label: '传真', value: 'fax', type: 'input', maxlength: 16 },
    {
      label: '详细地址',
      value: 'address',
      type: 'textarea',
      maxlength: 100,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    name: [
      {
        required: true,
        message: '请填写机构名称',
        trigger: 'change,blur',
      },
    ],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'change,blur' }],
    zipCode: [{ validator: proxy.$validate.zipCode, trigger: 'blur' }],
    mail: [{ validator: proxy.$validate.mail, trigger: 'blur' }],
    fax: [{ validator: proxy.$validate.fax, trigger: 'blur' }],
  },
  labelWidth: '120px',
})
const certificateOfBusinessInfo = ref({
  ref: null,
  data: {
    issuingDate: '',
    startDate: '',
    endDate: '',
  },
  fieldList: [
    {
      label: '证书编号',
      value: 'certificateNumber',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '注册地址',
      value: 'registeredAddress',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '公司类型',
      value: 'companyType',
      type: 'select-model',
      code: 'company_type',
      checkDefault: false,
    },
    {
      label: '注册资本(万元)',
      value: 'registeredCapital',
      type: 'money',
    },
    { label: '成立时间', value: 'establishedDate', type: 'date' },
    {
      label: '经营范围',
      value: 'businessScope',
      type: 'textarea',
      isSpecialInput: true,
      maxlength: 500,
    },
    {
      label: '发证机关',
      value: 'issuingAuthority',
      type: 'input',
      maxlength: 20,
    },
    { label: '发证日期', value: 'issuingDate', type: 'date' },
    { label: '营业开始日期', value: 'startDate', type: 'date' },
    { label: '营业截止日期', value: 'endDate', type: 'date' },
    {
      label: '营业执照',
      value: 'licenseFilePath',
      type: 'slot',
      className: 'not-br',
    },
  ],
  labelWidth: '120px',
  rules: {
    issuingDate: [{ validator: validateIssuingDate, trigger: 'change,blur' }],
    startDate: [{ validator: validateStartDate, trigger: 'change,blur' }],
    endDate: [{ validator: validateEndDate, trigger: 'change,blur' }],
    registeredCapital: [
      {
        validator: proxy.$validate.positiveMoneyNo,
        target: 'change,blur',
      },
    ],
    certificateNumber: [
      { validator: proxy.$validate.validatEn, target: 'change,blur' },
    ],
  },
})
const businessLicenseInfo = ref({
  ref: null,
  data: {
    issuingDate: '',
    startDate: '',
    endDate: '',
  },
  fieldList: [
    {
      label: '证书编号',
      value: 'certificateNumber',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '企业名称',
      value: 'companyName',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '注册地址',
      value: 'registeredAddress',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '法定代表人',
      value: 'legalRepresentative',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '企业负责人',
      value: 'responsiblePersons',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '质量管理人',
      value: 'qualityManager',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '经营范围',
      value: 'businessScope',
      type: 'textarea',
      isSpecialInput: true,
      maxlength: 500,
    },
    {
      label: '发证机关',
      value: 'issuingAuthority',
      type: 'input',
      maxlength: 20,
    },
    { label: '发证日期', value: 'issuingDate', type: 'date' },
    { label: '许可期限开始日期', value: 'startDate', type: 'date' },
    { label: '许可期限截止日期', value: 'endDate', type: 'date' },
    {
      label: '经营许可证',
      value: 'licenseFilePath',
      type: 'slot',
      className: 'not-br',
    },
  ],
  labelWidth: '120px',
  rules: {
    issuingDate: [{ validator: validateBIssuingDate, trigger: 'change,blur' }],
    startDate: [{ validator: validateBStartDate, trigger: 'change,blur' }],
    endDate: [{ validator: validateBEndDate, trigger: 'change,blur' }],
    certificateNumber: [
      { validator: proxy.$validate.validatEn, target: 'change,blur' },
    ],
  },
})

const businessRecordCertificate = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '备案编号',
      value: 'recordNumber',
      type: 'input',
      maxlength: 20,
    },
    { label: '备案日期', value: 'recordDate', type: 'date' },
    {
      label: '企业名称',
      value: 'businessName',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '住所',
      value: 'registeredAddress',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '经营场所',
      value: 'businessAddress',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '库房地址',
      value: 'warehouseAddress',
      type: 'textarea',
      maxlength: 100,
    },
    {
      label: '经营方式',
      value: 'businessType',
      type: 'select-model',
      code: 'business_type',
      checkDefault: false,
    },
    {
      label: '法定代表人',
      value: 'legalRepresentative',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '企业负责人',
      value: 'responsiblePersons',
      type: 'input',
      maxlength: 20,
    },
    {
      label: '经营范围',
      value: 'businessScope',
      type: 'textarea',
      isSpecialInput: true,
      maxlength: 500,
    },
    { label: '备注', value: 'remark', type: 'input', maxlength: 100 },
    {
      label: '证书附件',
      value: 'licenseFilePath',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    recordNumber: [
      {
        required: true,
        message: '请填写备案编号',
        trigger: 'change,blur',
      },
    ],
    recordDate: [
      {
        required: true,
        message: '请选择备案日期',
        trigger: 'change,blur',
      },
    ],
  },
  labelWidth: '120px',
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
const action = ref(import.meta.env.VITE_APP_BASE_API + '/pub/uploadfile')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  }
)
watch(
  () => formInfo.value.data.cities,
  (value) => {
    if (value.length) {
      formInfo.value.data.province = value[0]
      formInfo.value.data.city = value[1]
      formInfo.value.data.county = value[2]
    }
  }
)

onMounted(() => {
  if (props.data) {
    getDetails()
  }
})

function getDetails() {
  getOrgInformation(props.data).then((res) => {
    if (res) {
      formInfo.value.data = res.data.org || {}
      certificateOfBusinessInfo.value.data = res.data.businessLicense || {}
      businessLicenseInfo.value.data = res.data.businessPermit || {}
      businessRecordCertificate.value.data =
        res.data.businessRecordCertificate || {}
      let { province, city, county } = formInfo.value.data
      let cities = []
      if (province) {
        cities.push(province)
      }
      if (city) {
        cities.push(city)
      }
      if (county) {
        cities.push(county)
      }
      formInfo.value.data['cities'] = cities
    }
  })
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      certificateOfBusinessInfo.value.ref.validate((valid1) => {
        if (valid1) {
          businessLicenseInfo.value.ref.validate((valid2) => {
            if (valid2) {
              businessRecordCertificate.value.ref.validate((valid4) => {
                if (valid4) {
                  let api = ''
                  if (props.type === 'update') {
                    api = updateOrgInformation
                  }
                  certificateOfBusinessInfo.value.data.orgId =
                    formInfo.value.data.id
                  certificateOfBusinessInfo.value.data.licenseFilePath =
                    certificateOfBusinessInfo.value.data.licenseFilePaths &&
                    certificateOfBusinessInfo.value.data.licenseFilePaths
                      .length > 0
                      ? certificateOfBusinessInfo.value.data.licenseFilePaths.join(
                          ','
                        )
                      : ''
                  businessLicenseInfo.value.data.orgId = formInfo.value.data.id
                  businessLicenseInfo.value.data.licenseFilePath =
                    businessLicenseInfo.value.data.licenseFilePaths &&
                    businessLicenseInfo.value.data.licenseFilePaths.length > 0
                      ? businessLicenseInfo.value.data.licenseFilePaths.join(
                          ','
                        )
                      : ''

                  businessRecordCertificate.value.data.orgId =
                    formInfo.value.data.id
                  businessRecordCertificate.value.data.licenseFilePath =
                    businessRecordCertificate.value.data.licenseFilePaths &&
                    businessRecordCertificate.value.data.licenseFilePaths
                      .length > 0
                      ? businessRecordCertificate.value.data.licenseFilePaths.join(
                          ','
                        )
                      : ''
                  let data = {
                    org: formInfo.value.data,
                    businessLicense: certificateOfBusinessInfo.value.data,
                    businessPermit: businessLicenseInfo.value.data,

                    businessRecordCertificate:
                      businessRecordCertificate.value.data,
                  }
                  api(data).then((res) => {
                    if (res) {
                      emits('callback', true)
                      showDialog.value = false
                    }
                  })
                }
              })
            }
          })
        }
      })
    }
  })
}
function handleResponse(response) {
  return response
}
</script>
<style scoped>
/* :deep(.box-scroll-y) {
  height: calc(100% - 40px);
} */
</style>
